#include "Stack.h"

void StackInit(Stack* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

void StackPush(Stack* ps,StackDataType x)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		int newCapacity = ps->capacity == 0 ? 4 : 2 * (ps->capacity);
		StackDataType* tmp = (StackDataType*)realloc(ps->arr,sizeof(StackDataType)*newCapacity);
		if (tmp == NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newCapacity;
	}
	ps->arr[ps->size++] = x;
}

void StackPop(Stack* ps)
{
	assert(ps && ps->size);
	ps->size--;
}

StackDataType StackTopData(Stack* ps)
{
	assert(ps && ps->size);
	return ps->arr[ps->size - 1];
}

int StackSize(Stack* ps)
{
	assert(ps);
	return ps->size;
}

bool Stackif(Stack* ps)
{
	assert(ps);
	return ps->size == 0;
}

void StackDestroy(Stack* ps)
{
	assert(ps );
	free(ps->arr);
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}